package com.gdk.ksoft.ui.reporters;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.assembly.dbhelper.FreporterDbHelper;
import com.gdk.ksoft.ui.reporters.adapters.OrderStatementAdapter;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.gdk.ksoft.assembly.utils.system.TimeUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

/**
 * 历史开单日报查询
 */
public class HistoryOrderStatementActivity extends Activity {

    @ViewInject(R.id.phistoryorderstatement_etSearch)private EditText etSearch;//搜索框
    @ViewInject(R.id.phistoryorderstatement_txtStartDate)private TextView txtStartDate;//起始日期
    @ViewInject(R.id.phistoryorderstatement_txtEndDate)private TextView txtEndDate;//截止日期
    @ViewInject(R.id.phistoryorderstatement_txtOrderCount)private TextView txtOrderCount;//订单张数
    @ViewInject(R.id.phistoryorderstatement_txtGoodsKinds)private TextView txtGoodsKinds;//商品种类数
    @ViewInject(R.id.phistoryorderstatement_txtGoodsMoney)private TextView txtGoodsMoney;//商品金额
    @ViewInject(R.id.phistoryorderstatement_txtGoodsCount)private TextView txtGoodsCount;//商品数量
    @ViewInject(R.id.phistoryorderstatement_lstorder)private ListView lstOrder;//订单总数量
    private DbUtils dbUtils;//数据库操作对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_order_statement);
        ViewUtils.inject(this);
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        initActivity();//初始化activity
    }

    /**
     * 初始化activity
     */
    public void initActivity(){
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        int month = (calendar.get(Calendar.MONTH)+1);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        String monthStr = month<10?"0"+month:month+"";
        String dayStr = day<10?"0"+day:""+day;
        txtEndDate.setText(calendar.get(Calendar.YEAR)+"-"+monthStr+"-"+dayStr);
        calendar.add(Calendar.DAY_OF_MONTH, -SystemData.saleMan.cxddts);
        month = (calendar.get(Calendar.MONTH)+1);
        day = calendar.get(Calendar.DAY_OF_MONTH);
        monthStr = month<10?"0"+month:month+"";
        dayStr = day<10?"0"+day:""+day;
        txtStartDate.setText(calendar.get(Calendar.YEAR) + "-" + monthStr + "-" + dayStr);
    }

    /**
     * 列表项点击事件
     * @param av
     * @param view
     * @param position
     * @param itemId
     */
    @OnItemClick(value={R.id.phistoryorderstatement_lstorder})
    public void onItemClick(AdapterView<?> av,View view,int position,long itemId){
        HashMap<String,Object> item = (HashMap<String,Object>)lstOrder.getItemAtPosition(position);
        Intent intent = new Intent(this,HistoryOrderStatementDetailActivity.class);
        intent.putExtra("orderNo",item.get("xdjh").toString());//写入单据号
        startActivity(intent);
        overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
    }

    /**
     * 页面控件点击事件
     * @param view
     */
    @OnClick(value = {R.id.phistoryorderstatement_txtFindOrder,R.id.phistoryorderstatement_txtStartDate,
            R.id.phistoryorderstatement_txtEndDate})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.phistoryorderstatement_txtFindOrder://查找订单
                if(!isCanExcuteQuery()) return;//判断当前能否进行查询，或者限制查询的天数
                findHistoryOrder(this,dbUtils,etSearch.getText().toString(),
                        txtStartDate.getText().toString(),
                        txtEndDate.getText().toString()
                );
                break;
            case R.id.phistoryorderstatement_txtStartDate://起始时间
                showDatePickDialog(true);
                break;
            case R.id.phistoryorderstatement_txtEndDate://终止时间
                showDatePickDialog(false);
                break;
        }
    }

    /**
     * 显示日期选择对话框
     * @param isStartDate
     */
    public void showDatePickDialog(final boolean isStartDate){
        String dateString = txtStartDate.getText().toString();
        if(!isStartDate) dateString = txtEndDate.getText().toString();
        Calendar calendar = parserString2Date(dateString);
        new DatePickerDialog(this,new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                compareToCurrentDate(year,monthOfYear,dayOfMonth);
                String month = (monthOfYear+1<10?"0"+(monthOfYear+1):(monthOfYear+1)+"");
                String day = dayOfMonth<10?"0"+dayOfMonth:""+dayOfMonth;
                if(isStartDate)
                    txtStartDate.setText(year+"-"+month+"-"+day);
                else
                    txtEndDate.setText(year+"-"+month+"-"+day);
            }
        },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH))
                .show();
    }

    /**
     * 把字符串转换为日期
     * @param string
     * @return
     */
    public Calendar parserString2Date(String string){
        Date date = null;
        try{
            date = new SimpleDateFormat("yyyy-MM-dd").parse(string);
        }catch (Exception e){
            date = new Date();
        }
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        calendar.setTime(date);
        return calendar;
    }


    /**
     * 做时间对比
     * @param year
     * @param month
     * @param day
     * @return true - 符合查询要求   false - 不符合查询要求
     */
    public boolean compareToCurrentDate(int year,int month,int day) {
        Calendar currCalendar = Calendar.getInstance(Locale.CHINA);
        Calendar targetCalendar = Calendar.getInstance(Locale.CHINA);
        targetCalendar.set(year, month, day);
        if (TimeUtils.computeTimeSpan(currCalendar,targetCalendar) > SystemData.saleMan.cxddts) {//做时间对比
            Toast.makeText(this, "您只能操作前" + SystemData.saleMan.cxddts + "天的数据!请重新选择查询时间!", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }


    /**
     * 判断能否执行查询操作
     * @return
     */
    public boolean isCanExcuteQuery(){
        try {
            Calendar startCalendar = parserString2Date(txtStartDate.getText().toString());
            Calendar endCalendar = parserString2Date(txtEndDate.getText().toString());
            if(!compareToCurrentDate(startCalendar.get(Calendar.YEAR),startCalendar.get(Calendar.MONTH),
                    startCalendar.get(Calendar.DAY_OF_MONTH))) return false;
            if(!compareToCurrentDate(endCalendar.get(Calendar.YEAR),endCalendar.get(Calendar.MONTH),
                    endCalendar.get(Calendar.DAY_OF_MONTH))) return false;
            if(startCalendar.compareTo(endCalendar)>0) {
                Toast.makeText(this,"查询的末时间不能小于初时间!",Toast.LENGTH_SHORT).show();
                return false;
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 查询历史订单记录
     * @param keyword
     * @param startDate
     * @param endDate
     */
    public void findHistoryOrder(final Context context,final DbUtils dbUtils,final String keyword,final String startDate,final String endDate){
        new AsyncTask<Void,Void,Void>(){
            private ProgressDialog dialog = null;
            private String errorMessage = null;
            private List<HashMap<String,Object>> list = null;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在查询中...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    list = FreporterDbHelper.findHistoryOrder(dbUtils,keyword,startDate,endDate,1);
                }catch (Exception e){
                    e.printStackTrace();
                    errorMessage = e.getMessage();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errorMessage!=null){
                    Toast.makeText(context,"查询失败!原因："+errorMessage,Toast.LENGTH_SHORT).show();
                    return;
                }
                lstOrder.setAdapter(new OrderStatementAdapter(context,list));
            }
        }.execute();
    }


    /**
     * 页面返回
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.phistoryorderstatement_imgBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
